<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            top: 0;
            width: 200px;
            height: 200px;
            border: 1px solid #000;
            margin: 200px auto;
        }
    </style>
</head>

<body>
    <button class="qianjin">前进</button>
    <button class="houtui">后退</button>
    <div></div>

    <script>
        function animate(obj, target) {
            clearInterval(obj.timer)
            obj.timer = setInterval(function() {
                var step = (target - obj.offsetLeft) / 10
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (obj.offsetLeft >= target) {
                    //停止动画 本质是停止定时器
                    clearInterval(obj.timer)
                }
                obj.style.left = obj.offsetLeft + step + 'px'
            }, 60)
        }
        var div = document.querySelector('div')
        var btn = document.querySelector('.qianjin')
        var btn1 = document.querySelector('.houtui')

        btn.addEventListener('click', function() {
            animate(div, 700)

        })
        btn1.addEventListener('click', function() {
            animate(div, 200)
        })
    </script>
</body>

</html>